package bishi;

public class demo2 {

    public final int maxCount;
    public final Object lock = new Object();
    private int current = 1;
    public  demo2(int maxCount){
        this.maxCount = maxCount;
    }

    // 打印奇数
    public void printOdd(){
        synchronized (lock){
            try {

                while (current <= maxCount){
                    if(current%2==0){
                        lock.wait();
                        continue;
                    }
                    System.out.println(Thread.currentThread().getName() +":" + current);
                    current = current + 1;

                    lock.notify();

                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    // 打印偶数
    public void printDdd(){
        synchronized (lock){
            try {

                while (current <= maxCount){
                    if(current%2!=0){
                        lock.wait();
                        continue;
                    }
                    System.out.println(Thread.currentThread().getName() +":" + current);
                    current = current + 1;

                    lock.notify();

                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        demo2 demo2 = new demo2(100);
        Thread t1 = new Thread(demo2::printOdd, "printOdd");
        Thread t2 = new Thread(demo2::printDdd, "printDdd");

        t1.start();
        t2.start();
    }

}
